package com.cw.jeeyt.controller.git;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cw.jeeyt.api.dto.response.JsonResultDto;
import com.cw.jeeyt.common.DataTable;
import com.cw.jeeyt.common.ResultData;
import com.cw.jeeyt.common.enums.EnumOperateFlag;
import com.cw.jeeyt.common.utils.StringUtil;
import com.cw.jeeyt.common.web.BaseController;
import com.cw.jeeyt.service.bo.git.GitProjectBo;
import com.cw.jeeyt.service.bo.git.NewGitBranchBo;
import com.cw.jeeyt.service.directive.PageDictDirective;
import com.cw.jeeyt.service.directive.PermissionDirective;
import com.cw.jeeyt.service.intf.git.GitProjectService;
import com.cw.lang.common.utils.CollectionUtil;
import com.cw.lang.common.utils.PageUtil;
import com.cw.lang.mybatis.dto.PageInfo;
import com.cw.lang.mybatis.dto.PageParam;

/**
 * git项目信息控制层
 *
 * @author chenw
 * @version 1.0.0
 */
@Controller
@RequestMapping("/gitProject")
public class GitProjectController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(GitProjectController.class);
    @Resource
    private GitProjectService gitProjectService;

    /**
     * 跳转到git项目信息列表查询页面
     *
     * @throws Exception
     */
    @RequestMapping(value = "/query")
    public ModelAndView query() throws Exception {

        ModelAndView mv = new ModelAndView("git/gitProject_index");
        mv.addObject("permission", new PermissionDirective());
        mv.addObject("PageDict", new PageDictDirective());
        return mv;
    }

    /**
     * 跳转到git项目信息列表查询页面
     */
    @RequestMapping(value = "/to-newBranch")
    public ModelAndView newBranch(String projectIds) {

        ModelAndView mv = new ModelAndView("git/gitProject_newBranch");
        //获取所有项目信息
        if (StringUtil.isEmpty(projectIds)) {
            return mv;
        }
        List<GitProjectBo> projectBos = gitProjectService.selectListByProjectIds(projectIds);
        StringBuilder projectCodes = new StringBuilder();
        int i = 0;
        for (GitProjectBo project : projectBos) {
            if (i == 0) {
                projectCodes.append(project.getProjectCode());
            } else {
                projectCodes.append("," + project.getProjectCode());
            }
            i++;
        }
        mv.addObject("projectIds", projectIds);
        mv.addObject("projectCodes", projectCodes.toString());
        return mv;
    }

    /**
     * 加载DataTable列表数据
     *
     * @param dataTable 请求数据
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/listGitProject")
    public ResultData listGitProject(@RequestBody DataTable dataTable) throws Exception {

        GitProjectBo gitProjectBo = JSONObject.parseObject(JSON.toJSONString(dataTable.getQueryCond()),
            GitProjectBo.class);
        if (gitProjectBo == null) {
            gitProjectBo = new GitProjectBo();
        }
        PageInfo<GitProjectBo> pageInfo = gitProjectService.selectPage(gitProjectBo, PageParam.Builder.getInstance()
            .addPageNum(PageUtil.calPageNum(dataTable.getStart(), dataTable.getLength()))
            .build());
        return ResultData.builder()
            .draw(dataTable.getDraw())
            .data(CollectionUtil.isNotEmpty(pageInfo.getList())?pageInfo.getList():new ArrayList())
            .recordsTotal(pageInfo.getTotal())
            .recordsFiltered(pageInfo.getTotal())
            .build();
    }

    /**
     * 跳转到git项目信息表单页面
     *
     * @param operation 操作  add 新增 edit修改 view查看
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-form")
    public ModelAndView editForm(Long id, String operation) throws Exception {

        ModelAndView mv = new ModelAndView("git/gitProject_form");
        GitProjectBo gitProjectBo = null;
        if (EnumOperateFlag.ADD.getCode()
            .equals(operation)) {
            gitProjectBo = new GitProjectBo();
        } else {
            gitProjectBo = gitProjectService.selectByKey(id);
        }
        mv.addObject("gitProject", gitProjectBo);
        mv.addObject("operation", operation);
        mv.addObject("PageDict", new PageDictDirective());
        mv.addObject("permission", new PermissionDirective());
        return mv;
    }

    /**
     * 根据操作类型保存git项目信息数据
     *
     * @param gitProjectBo
     * @param operation add 新增  edit 修改
     */
    @ResponseBody
    @RequestMapping(value = "/saveGitProject", method = RequestMethod.POST)
    public JsonResultDto saveGitProject(GitProjectBo gitProjectBo, String operation) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            if (operation.equals(EnumOperateFlag.ADD.getCode())) {
                gitProjectService.addGitProject(gitProjectBo);
            } else if (operation.equals(EnumOperateFlag.EDIT.getCode())) {
                gitProjectService.modifyGitProject(gitProjectBo);
            }
            jsonResultDto.setMsg("保存成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            jsonResultDto.setMsg("保存失败:" + e.getMessage());

            e.printStackTrace();
            logger.error("保存git项目信息失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 拉取新分支
     *
     * @param newGitBranchBo
     */
    @ResponseBody
    @RequestMapping(value = "/newBranch", method = RequestMethod.POST)
    public JsonResultDto newBranch(NewGitBranchBo newGitBranchBo) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            gitProjectService.newBranch(newGitBranchBo);
            jsonResultDto.setMsg("分支新建成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            jsonResultDto.setMsg("保存失败:" + e.getMessage());
            logger.error("保存git项目信息失败,{}" , e);
        }
        return jsonResultDto;
    }

    /**
     * 删除git项目信息
     *
     * @param gitProjectBo
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public JsonResultDto delete(GitProjectBo gitProjectBo) throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            gitProjectService.deleteGitProject(gitProjectBo);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();

            jsonResultDto.setMsg("删除失败：" + e.getMessage());
            logger.error("删除git项目信息失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 下载git项目信息
     *
     * @param projectIds
     */
    @RequestMapping(value = "/downloadCode")
    @ResponseBody
    public JsonResultDto downloadCode(String projectIds) {

        JsonResultDto result = new JsonResultDto(false);
        try {
            //gitProjectService.downloadCode(projectIds);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setMsg("同步git项目代码失败：" + e.getMessage());
            e.printStackTrace();
            logger.error("同步git项目代码失败：" + e.getMessage());
        }
        return result;
    }
}
